/**
 *
 */
package com.geetour.columbus.core.mail;

import java.io.File;
import java.util.Map;

import javax.mail.internet.MimeMessage;

import org.apache.velocity.app.VelocityEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.ui.velocity.VelocityEngineUtils;

/**
 * @author ChenKai
 */
public class EmailService {

	private EmailAppConfig emailAppConfig;
	private VelocityEngine velocityEngine;

	@Autowired
	public void setEmailAppConfig(EmailAppConfig emailAppConfig) {
		this.emailAppConfig = emailAppConfig;
	}

	@Autowired
	public void setVelocityEngine(VelocityEngine velocityEngine) {
		this.velocityEngine = velocityEngine;
	}

	public void sendEmail(final Map<String, Object> model,
			final String subject, final String vmfilePath, final String[] mailTo,
			final String[] files) {

		MimeMessagePreparator preparator = new MimeMessagePreparator() {
			public void prepare(MimeMessage mimeMessage) throws Exception {
				MimeMessageHelper message = new MimeMessageHelper(mimeMessage,true, "GBK");
				message.setTo(mailTo);// 设置接收方的email地址
				message.setSubject(subject);// 设置邮件主题
				message.setFrom("pms@sogou-inc.com");// 设置发送方地址
				String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, vmfilePath, "GBK", model);
				message.setText(text, true);
				FileSystemResource file;
				// 添加附件
				for (String s : files) {
					file = new FileSystemResource(new File(s));// 读取附件
					message.addAttachment(s, file);// 向email中添加附件
				}
			}
		};
		JavaMailSender mailSender = emailAppConfig.mailSender();
		mailSender.send(preparator);// 发送邮件
	}
}
